<!--
 - MineAdmin is committed to providing solutions for quickly building web applications
 - Please view the LICENSE file that was distributed with this source code,
 - For the full copyright and license information.
 - Thank you very much for using MineAdmin.
 -
 - @Author X.Mo<root@imoi.cn>
 - @Link   https://gitee.com/xmo/mineadmin-vue
-->
<template>
    <div class="ma-content-block lg:flex justify-between p-4">
      <!-- CRUD 组件 -->
      <ma-crud :options="crud" :columns="columns" ref="crudRef">
        <!-- 状态列 -->
        <template #status="{ record }">
          <div>{{record.status == 1?'正常':'停用'}}</div>
        </template>
        <!-- 头像列 -->
        <template #avatar="{ record }">
          <a-avatar>
            <img :src="record.avatar || $url + 'avatar.jpg'" style="object-fit: cover" />
          </a-avatar>
        </template>
  
        <template #dept_ids="{ record }">
          <a-tooltip :content="record.depts[0].name">
            <div>{{record.depts[0].name}}</div>
          </a-tooltip>
        </template>
        
        
        <!-- 操作列扩展 -->
        <template #operationAfterExtend="{ record }">
          <a-link @click="selectOperation('resetPassword',record.id)"> 重置密码</a-link>
        </template>
      </ma-crud>
    </div>
  </template>
  
  <script setup>
    import { ref, onMounted, reactive, computed,defineProps } from 'vue'
    import MaTreeSlider from '@cps/ma-treeSlider/index.vue'
    import dept from '@/api/system/dept'
    import user from '@/api/system/user'
    import commonApi from '@/api/common'
    import { Message, Modal } from '@arco-design/web-vue'
    import addressVue from '@/views/prediction/address/index.vue'
    import { before } from 'lodash'
    const depts = ref([])
    const homePageList = ref([])
    const crudRef = ref()
  
    const setHomeVisible = ref(false)
    const userid = ref()
    const homePage = ref('')
    const address = ref()
    const visibleAddress = ref(false)
    const props = defineProps({
        dept_id:{
            type: Number,
            default:0,
        }
    })
    onMounted(()=>{
        crudRef.value.requestData()
    })
    
  
  
    let isRecovery = computed(() => crudRef.value ? crudRef.value.isRecovery : false )
  
    const addressTap = (row) => {
      address.value.open(row)
      visibleAddress.value = true
    }
  
    const switchDept = (id) => {
      crudRef.value.requestParams = id[0] === 'all' ? { dept_id: undefined } : { dept_id: id[0] }
      crudRef.value.requestData()
    }
  
    const changeStatus = async (status, id) => {
      const response = await user.changeStatus({ id, status })
      if (response.success) {
        Message.success(response.message)
      }
    }
  
    const updateCache = id => {
      user.clearCache(id).then(res => {
        if (res.success) Message.success(res.message)
      })
    }
    
    const resetPassword = (id) => {
      user.initUserPassword({ id }).then(res => res.success && Message.success(res.message) )
    }
  
    const saveHomePage = (done) => {
      user.setHomePage({ id: userid.value, dashboard: homePage.value }).then(res => {
        res.success && Message.success(res.message)
      })
      done(true)
    }
  
    const selectOperation = (value, id) => {
      if (value === 'resetPassword') {
        Modal.info({
          title: '提示',
          content: '确定将该用户密码重置为 123456 吗？',
          simple: false,
          onBeforeOk: (done) => {
            resetPassword(id)
            done(true)
          }
        })
        return
      }
  
      if (value === 'updateCache') {
        updateCache(id)
        return
      }
  
      if (value === 'setHomePage') {
        setHomeVisible.value = true
        userid.value = id
        return
      }
    }
  
    const crud = reactive({
      id: 'financeLedgerUser',
      pk:'id',
      api: user.getPageList,
      recycleApi: user.getRecyclePageList,
      searchColNumber: 5,
      showIndex: false,
      autoRequest:false,
      rowSelection: { showCheckedAll: true },
      operationColumn: true,
      operationColumnWidth: 200,
      add: { show: true, api: user.save, auth: ['system:user:save'],text: '新增用户' },
      edit: { show: true, api: user.update, auth: ['system:user:update'] },
      delete: {
        show: true,
        api: user.deletes, auth: ['system:user:delete'],
        realApi: user.realDeletes, realAuth: ['system:user:realDeletes']
      },
      recovery: { show: true, api: user.recoverys, auth: ['system:user:recovery']},
      import: { show: false, url: 'system/user/import', templateUrl: 'system/user/down loadTemplate', auth: ['system:user:import'] },
      export: { show: true, url: 'system/user/export', auth: ['system:user:export'] },
      formOption: {
        width: 800,
        layout: [
          { formType: 'grid', cols: [ { span: 24, formList: [ { dataIndex: 'avatar' }] }]  },
          { formType: 'grid', cols: [ { span: 12, formList: [ { dataIndex: 'username' }] }, { span: 12, formList: [{ dataIndex: 'dept_ids' }] }]  },
          { formType: 'grid', cols: [ { span: 12, formList: [ { dataIndex: 'password' }] }, { span: 12, formList: [{ dataIndex: 'nickname' }] }]  },
          { formType: 'grid', cols: [ { span: 12, formList: [ { dataIndex: 'role_ids' }] }, { span: 12, formList: [{ dataIndex: 'phone' }] }]  },
          { formType: 'grid', cols: [ { span: 24, formList: [ { dataIndex: 'wx_user_type' }] }] },
          { formType: 'grid', cols: [ { span: 24, formList: [ { dataIndex: 'status' }] }] },
          { formType: 'grid', cols: [ { span: 24, formList: [ { dataIndex: 'remark' }] }] },
        ]
      },
      // isDbClickEdit: false,
      beforeOpenEdit: (record) => {
        if (record.id === 1) {
          Message.error('创始人不可编辑')
          return false
        }
        return true
      },
      beforeDelete: (ids) => {
        if (ids.includes(1)) {
          Message.error('创始人不可删除')
          return false
        }
        return true
      },
      beforeRequest:(params)=>{
        params.dept_ids = props.dept_id
      },
      afterRequest:(params)=>{
        params.map((v,i)=>{
          if(v.depts.length != 0){
            v.dept_ids = v.depts[0].id
          }else{
            v.depts.push({name:''})
            v.dept_ids = ''
          }
          
        })
      }
      
    })
  
    const columns = reactive([
      { title: 'ID', dataIndex: 'id', addDisplay: false, editDisplay: false, width: 50, hide: true },
      {
        title: '头像', dataIndex: 'avatar', width: 75, formType: 'upload', returnType: 'url',
        type: 'image', rounded: true, labelWidth: '86px'
      },
      { 
        title: '账户', dataIndex: 'username', width: 130,  addDisabled: false, editDisabled: false,
        commonRules: [{ required: true, message: '账户必填' }]
      },
      {
        title: "所属公司",
        dataIndex: "dept_ids",
        align: "center",
        formType: "select",
        width: 200,
        addDefaultValue:props.dept_id,
        dict: {
          // 远程通用接口请求，新版代码生成都有一个 remote 接口
          remote: "system/dept/remote",
          // 指定组件接收的props
          props: { label: "name", value: "id" },
          // 开启分页
          openPage: false,
          // 远程请求配置项
          remoteOption: {
            // 按用户名排序
            sort: { id: "desc" }, // 如果不指定排序方式，默认为正序排序
            // 设置查询的字段
            select: ["id", "name"],
            // 设置数据过滤
            filter: {
              status: ['=',1]
            },
            // 关联模型
            relations: [],
          },
        },
      },
      {
        title: '登录密码', dataIndex: 'password', width: 120 ,hide:true,
      },
      { title: '昵称', dataIndex: 'nickname', width: 120 , },
      { 
        title: '角色', dataIndex: 'role_ids', width: 120, formType: 'select', multiple: true,
        dict: { url: 'system/role/list', props: { label: 'name', value: 'id' } }, hide: true, 
        commonRules: [{ required: true, message: '角色必选' }],
        editDefaultValue: async (record) => {
          const response = await user.read(record.id)
          return response.data.roleList.map(item => item.id )
        }
      },
      {
        title: '手机', dataIndex: 'phone', width: 150, 
        commonRules: [{ match: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码' }]
      },
      // { 
      //   title: '岗位', dataIndex: 'post_ids', width: 120, formType: 'select', multiple: true,
      //   dict: { url: 'system/post/list', props: { label: 'name', value: 'id' } }, hide: true,
      //   editDefaultValue: async (record) => {
      //     const response = await user.read(record.id)
      //     const ids = response.data.postList.map(item => item.id )
      //     return ids
      //   }
      // },
      // {
      //   title: '邮箱', dataIndex: 'email', width: 200, search: true,
      //   commonRules: [{ type: 'email', message: '请输入正确的邮箱' }]
      // },
      // {
      //   title: '用户类型', dataIndex: 'user_type', width: 100, search: true, formType: 'radio',
      //   dict: {
      //     name: 'user_type',
      //     props: { label: 'title', value: 'key' }, translation: true,
      //     tagColors: { '100': 'orange', '200': 'blue', '300': 'green'}
      //   },
      //   addDefaultValue: '100', labelWidth: '86px'
      // },
      {
      title: "用户类别",
      dataIndex: "wx_user_type",
      formType: "radio",
      addDefaultValue: '1',
      dict: {
        data: [
          {
            label: "客户端",
            value: "1"
          },
          {
            label: "司机端",
            value: "2"
          },
          {
            label: "装卸端",
            value: "3"
          },
          {
            label: "巡查端",
            value: "4"
          },
          {
            label: "后台端",
            value: "5"
          },
          {
            label: "领导端",
            value: "6"
          },
          {
            label: "财务端",
            value: "7"
          }
        ],
        translation: true
      }
    },
      {
        title: '状态', dataIndex: 'status', width: 100,  formType: 'radio',
        dict: { name: 'data_status', props: { label: 'title', value: 'key' } },
        addDefaultValue: '1', labelWidth: '86px'
      },
      
      {
        title: '备注', dataIndex: 'remark', width: 180, hide: true,
        formType: 'textarea', labelWidth: '86px'
      },
      {
        title: '注册时间', dataIndex: 'created_at', width: 180, addDisplay: false, editDisplay: false,
         formType: 'range'
      },
    ])
  </script>
  
  <script>
  export default { name: 'financial:financeLedgerUser' }
  </script>
  
  <style scoped>
  
  </style>